<template>
  <div
    class="echarts_box"
    ref="chart"
    @click="handleBoxClick" 
  ></div>
</template>
<script>

export default {
  name: "normalPie",
  props: {
    option: Object,
    data: Array,
  },
   data(){
    return{
      pieDatas:[],
      timeer: "",
      defaultColors:["#286AF7","#00BAE9","#3BD242","#DFDF01","#FD9802","#F9691A","#F14E4E","#AE0CE3","#6E11EC","#4911EC"]
    }
  },
  computed: {
    colors(){
      return this.option.colors;
    }
  },
  methods: {
    init(){
      this.pieDatas = JSON.parse(JSON.stringify(this.data));
        this.initChart();
    },
    initChart() {
      const chart = this.$refs.chart;
      if (chart) {
        if(this.myEchart){
          this.myEchart.dispose();
        }
        let myEchart = echarts.init(chart);
        this.myEchart = myEchart;
        let barColor = this.option.barColor;
        let nameMaxLength = Math.max(...this.pieDatas.map(item=>item.name.length))
        console.log(this.option.title1Text,"this.option.title1Text")
        let option = {
          color: this.option.barColor || this.defaultColors,
          grid: {
            left: this.option.gridX || 0,
            right: this.option.gridX2 || 0,
            top: this.option.gridY || 0,
            bottom: this.option.gridY2 || 0,
            containLabel: true,
          },
          title: [
            {
              show: this.hasProp(this.option.title1, "show", false),
              text: this.option.title1.text||'',
              x:this.option.title1.left || "center",
              y: this.option.title1.top|| "center",
              textStyle: {
                fontWeight: "bold",
                color: this.option.title1.fontcolor || "#000",
                fontSize: this.option.title1.fontSize,
              },
            },
            {
              show: this.hasProp(this.option.title2, "show", false),
              text:this.option.title2.text||'',
              x: this.option.title2.left|| "center",
              y: this.option.title2.top|| "35%",
              textStyle: {
                fontWeight: "normal",
                color: this.option.title2.fontcolor || "#fff",
                fontSize:this.option.title2.fontSize,
              },
            },
          ],
          tooltip: {
            show: true,
            trigger: "item",
            backgroundColor:'rgba(50,50,50,0.7)',
            borderColor:'#333',
            textStyle:{
              color:'#fff'
            }
          },
          legend: {
            show: this.hasProp(this.option, "legend", false),
            // data: legendData,
            // type:'scroll',
            // selectedMode: this.option.legendAlertTanc?false:true,
            // selectedMode: 'single',
            orient: this.option.legendOrient || "horizontal",
            left: this.option.legendPositionLeft || "center",
            top: this.option.legendPositionTop || 0,
            right: this.option.legendPositionRight || "auto",
            bottom: this.option.legendPositionBottom || "auto",
            icon: this.hasProp(this.option, "legendIcon", "circle"),
            itemWidth: 10,
            itemHeight: 9,
            itemGap: this.option.legendItemGap || 10,
            // width: this.option.legendWidth || "100%",
            textStyle: {
              fontSize: this.option.nameFontSize || 14,
              color: this.option.nameColor || "#fff",
              rich:{
                name:{
                  width: nameMaxLength*(this.option.nameFontSize || 14),
                  
                },
                 legendShowPercentColor:{
                    color:this.option.legendShowValueColor||"#333",
                     lineHeight:15,
                   fontSize: this.option.nameFontSize || 14,

                },
                 legendShowValue:{
                    color:this.option.legendShowValueColor||"#333",
                   fontSize: this.option.nameFontSize || 14,
                }
              }
            },
            formatter: (this.hasProp(this.option, "legendShowPercent", false) || this.hasProp(this.option, "legendShowValue", false))
              ? (name)=> {
                  var datas = this.pieDatas;
                  let total = 0,showValue=this.hasProp(this.option, "legendShowValue", false),showPercent=this.hasProp(this.option, "legendShowPercent", false);
                  let showFh=this.hasProp(this.option, "legendshowFh", false)
                  datas.map(item=>{
                    total += (item.value-0)
                  })
                  let valueIndex = datas.map(item=>item.name).indexOf(name);
                  return [
                    '{name|'+name + "} ",
                  '{legendShowValue|'+(showPercent?((datas[valueIndex].value / total) * 100).toFixed(this.option.valueFixed||2)+"%":'')+'}',
                   (showFh?'\n':'   '),
                  '{legendShowPercentColor|'+(showValue?datas[valueIndex].value+(this.option.legendValueUnit||''):'')+'}'].join('');
                }
              : "{name}",
          },
          series: [
            {
              name: this.option.chartName || '值',
              type: "pie",
              roseType: this.hasProp(this.option, "roseType", false),
              center: this.option.center || ["50%", "50%"],
              radius: this.option.radius || "50%",
              label: {
                show: this.hasProp(this.option, "labelShow", false),
                position: this.hasProp(
                  this.option,
                  "labelPosition",
                  "outside"
                ), //inside/center
                formatter: this.hasProp(
                  this.option,
                  "labelFormatter",
                  "{d}%"
                ),
                textStyle: {
                  color: this.option.nameColor || "#fff",
                  fontSize: this.option.nameFontSize || 14,
                },
              },
              labelLine: {
                show: this.hasProp(this.option, "labelLineShow", true),
                length: this.option.labelLineLength || 15,
                length2: this.option.labelLineLength2 || 5,
                lineStyle: {
                  color: "#C0C0C0",
                  opacity: 0.5,
                },
              },
              data: this.pieDatas.map((item,i)=>{
                item.itemStyle = {
                  normal:{
                    color: this.getColor(barColor,i)
                  },
                  emphasis: {
                    shadowBlur: 10,
                    shadowOffsetX: 0,
                    shadowColor: "rgba(0, 0, 0, 0.5)",
                  },
                  
                }
                return item
              }),
            },
          ],
        };
        this.myEchart.resize();
        myEchart.setOption(option, true);
        // myEchart.on('legendselectchanged', (obj)=> {
        //   var selected = obj.selected;
        //   var legend = obj.name;
        //   if(this.option.legendAlertTanc){
        //     let valueIndex = this.pieDatas.map(item=>item.name).indexOf(legend);
        //     this.alertTanc('name',this.pieDatas[valueIndex])
        //   }
        //   console.log(obj)
        // });
        // myEchart.on('click', (obj)=> {
        //   this.alertTanc('value',obj.data);
        // });
        myEchart.off("legendselectchanged");
        myEchart.on("legendselectchanged",(params)=>{
            var isSelected = params.selected[params.name];
            if(isSelected == false){
                myEchart.dispatchAction({
                    type:'legendToggleSelect',
                    name: params.name
                });
                myEchart.dispatchAction({
                    type:'highlight ',
                    name: params.name
                });
                let index = this.pieDatas.map(item=>item.name).indexOf(params.name);
                if(index>-1){
                  this.handleChartClick('name',this.pieDatas[index]);
                }
            }
        });
     
      }
    },
    handleChartClick(field,data,colIndex){
      /**
       field 点击字段
       data 行数据
       */
      if(!this.option.tancShowByBox && field && this.option.tanc && this.option.tanc.showTanc){
        let params = JSON.parse(JSON.stringify(this.option.tanc.table.params||{}));
        let alias = this.option.tanc.clickDataKeyAlias || (this.option.tanc.clickDataKey || field),//拼接参数的字段名
            prop = this.option.tanc.clickDataKey || field;//拼接参数取哪个字段的值
        params[alias] = data[prop];
          this.$alert({
            title: this.option.tanc.title,
            url: this.option.tanc.url,
            urlParams:{},
            type: this.option.tanc.type,
            option: this.option.tanc.option,
            table:{
              showPage:this.option.tanc.table.showPage||false,
              pageSizeField:'',
              pageIndexField:'',
              dataType: this.option.tanc.table.dataType||0,
              url:this.option.tanc.table.url||'',
              params:  Object.assign(this.option.tanc.table.params||{},params),
              columns:this.option.tanc.table.columns,
              data: this.option.tanc.table.data,
            },
            searchColumns: this.option.tanc.searchColumns||[],
            tabsDatas: this.option.tanc.tabsDatas||[],
            tanc: this.option.secTanc
          })
      }
    },
    handleBoxClick(){
      if(this.option.tancShowByBox && this.option.tanc && this.option.tanc.showTanc){
        this.$alert({
            title: this.option.tanc.title,
            url: this.option.tanc.url,
            // urlParams:{},
            type: this.option.tanc.type,
            table:{
              showPage:this.option.tanc.table.showPage||false,
              pageSizeField:'',
              pageIndexField:'',
              dataType: this.option.tanc.table.dataType||0,
              url:this.option.tanc.table.url||'',
              params:  Object.assign(this.option.tanc.table.params||{},{}),
              columns:this.option.tanc.table.columns||[],
              data: this.option.tanc.table.data||[],
            },
            option: this.option.tanc.option||{},
            searchColumns: this.option.tanc.searchColumns||[],
            tabsDatas: this.option.tanc.tabsDatas||[],
            tanc: this.option.secTanc    
          })
      }
    },
    alertTanc(field,data){
      console.log(field,data);
      if(field && this.option.tanc && this.option.tanc.showTanc){
        let params = JSON.parse(JSON.stringify(this.option.tanc.table.params||{}));
        let alias = this.option.tanc.clickDataKeyAlias || (this.option.tanc.clickDataKey || field),//拼接参数的字段名
            prop = this.option.tanc.clickDataKey || field;//拼接参数取哪个字段的值
        params[alias] = data[prop];
          this.$alert({
            title: this.option.tanc.title,
            // url: this.option.tanc.url,
            // urlParams:{},
            type: this.option.tanc.type,
            table:{
              showPage:this.option.tanc.table.showPage||false,
              pageSizeField:'',
              pageIndexField:'',
              dataType: this.option.tanc.table.dataType||0,
              url:this.option.tanc.table.url||'',
              params:  Object.assign(this.option.tanc.table.params,params),
              columns:this.option.tanc.table.columns,
              data: this.option.tanc.table.data,
            },
            option: this.option.tanc.option,
            searchColumns: this.option.tanc.searchColumns||[],
            tabsDatas: this.option.tanc.tabsDatas||[],
            tanc: this.option.secTanc    
          });
          
      }

    },
    getColor(colors, i, isFirst, orient) {
      let color = colors && colors[i];
      if (color && (typeof color == 'object')) {
        if (isFirst) {
          return color.color1;
        }
        orient = orient || "horizontal";
        if (orient == "vertical") {
          return new echarts.graphic.LinearGradient(0,0,1,0,
            [
              {
                offset: 0,
                color: color.color1,
              },
              {
                offset: color.postion || 1,
                color: color.color2 || color.color1,
              },
            ],
            false
          );
        }
        return new echarts.graphic.LinearGradient(0,0,0,1,
          [
            {
              offset: 0,
              color: color.color1,
            },
            {
              offset: color.postion || 1,
              color: color.color2 || color.color1,
            },
          ],
          false
        );
      } else if(!color && (this.colors && this.colors[i])){
        return this.colors[i];
      } else {
        return this.defaultColors[i];
      }
    },
     hasProp(obj, field, defaultValue) {
      if (obj.hasOwnProperty(field)) {
        return obj[field];
      } else {
        return defaultValue;
      }
    },
  },
  mounted() {
    this.init();
  },
  watch: {
    option: {
      handler(val, oldval) {
        if(val && JSON.stringify(val) != '{}') this.init();
      },
      deep: true,
    },
     data: {
      handler(val, oldval) {
        if(val) this.init();
      },
      deep: true,
    },
  },
 
};
</script>
<style scoped>
.echarts_box {
  width: 100%;
  height:100%;
}
</style>